package vcp.controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;

import javax.swing.JOptionPane;

import control.SimpleClient;
import control.customTimestamp;
import db.parking.beans.Orders;
import vcp.common.AbstractController;
import vcp.common.IController;
import vcp.gui.forms.CancelOrderForm;
import vcp.gui.forms.OrderOccasionalForm;
import vcp.gui.forms.OrderSubscriptionForm;
import vcp.gui.forms.OrderTemporaryForm;
import vcp.gui.forms.OrderTrackForm;
import vcp.gui.forms.validators.DateValidator;
import vcp.gui.forms.validators.EmailValidator;
import vcp.gui.forms.validators.NumericValidator;
import vcp.gui.forms.validators.Time24HoursValidator;
import vcp.models.OrdersModel;
import vcp.views.OrderGuestView;
import vcp.models.*; 

import java.sql.Timestamp;


public class OrdersGuestController extends AbstractController implements
		ActionListener, IController

{
	
	private HashMap<String, Object> models = new HashMap<String, Object>();

	// private OrdersModel model;
	private OrderGuestView view;

	@Override
	public void actionPerformed(ActionEvent eve) {
		if (eve.getActionCommand().equals("orderOccasional")) {
			CreateOccasionalOrder();
		} else if (eve.getActionCommand().equals("orderTemporary")) {
			CreateTemporaryOrder();
		} else if (eve.getActionCommand().equals("cancelOrder")) {
			CancelOrder();
		} else if (eve.getActionCommand().equals("orderTrack")) {
			TrackOrder();
		}
	}

	private void CreateOccasionalOrder() {
		boolean isValidForm=false;
		Orders bean = new Orders();
		NumericValidator verifyID = new NumericValidator();
		Time24HoursValidator verifyTime = new Time24HoursValidator();
		DateValidator verifyDate = new DateValidator();
		EmailValidator verifyEmail = new EmailValidator();

		
		OrderOccasionalForm form = view.getOrderOccasionalViewForm();
        if(form.getTextCID().getText().isEmpty() 
           || form.getCarNo_field().getText().isEmpty()
           || form.getEmail_field().getText().isEmpty()
           || form.gethTime_field().getText().isEmpty()
           || form.getmTime_field().getText().isEmpty()
           )
        {
        	JOptionPane.showMessageDialog(null,"Please fill in all fields","Invalid Input Error", JOptionPane.ERROR_MESSAGE);
		    isValidForm = false;
		    return;
        }
        
        //Parse all data	
		String ID = form.getTextCID().getText();
		String carNo = form.getCarNo_field().getText();
		String email = form.getEmail_field().getText();
		int leaveHours = Integer.parseInt(form.gethTime_field().getText());
		int leaveMinutes = Integer.parseInt(form.getmTime_field().getText());
		String time = form.gethTime_field().getText()+":"+form.getmTime_field().getText(); 
		int day=form.getDateChooser().getJCalendar().getDayChooser().getDay();
		int month=form.getDateChooser().getJCalendar().getMonthChooser().getMonth()+1;
		int year=form.getDateChooser().getJCalendar().getYearChooser().getYear();
		String date = Integer.toString(day)+"/"+ Integer.toString(month) +"/"+ Integer.toString(year);
		String dateFormat = "dd/MM/yyyy";
		
		//Input Validity Check
		if (ID.equals("") || carNo.equals("") || Integer.parseInt(ID)<0 || !verifyID.validate(carNo)) {
			JOptionPane.showMessageDialog(null,"Invalid ID Entered,Please Re-Enter","Invalid Input Error", JOptionPane.ERROR_MESSAGE);
			isValidForm = false;
		}
		else if (time.equals("") || !verifyTime.validate(time)) {
				JOptionPane.showMessageDialog(null,"Invalid Time Entered,Please Re-Enter","Invalid Time Error", JOptionPane.ERROR_MESSAGE);
				isValidForm = false;
		}
		else if (date.equals("") || !verifyDate.isThisDateValid(date, dateFormat)) {
			JOptionPane.showMessageDialog(null,"Invalid Date Entered,Please Re-Enter","Invalid Date Error", JOptionPane.ERROR_MESSAGE);
			isValidForm = false;
	   }
	   else if (email.equals("") || !verifyEmail.validate(email)) {
			JOptionPane.showMessageDialog(null,"Invalid Email Entered,Please Re-Enter","Invalid Email Error", JOptionPane.ERROR_MESSAGE);
			isValidForm = false;
	   }
	   else{
			isValidForm = true;
		}
		
		if(isValidForm==true){
			 try {
				//create new Timestamp for the time the user wants to leave the lot
				Timestamp leaveTime=customTimestamp.makeTimestamp(year,month,day,leaveHours,leaveMinutes,02,02);
				bean.setUid(ID);
				bean.setType("Occasional");
				bean.setCarNo(carNo);
				bean.setLeaveTime(leaveTime);
				bean.setLotNo(1);
				bean.setEmail(email);
				bean.setStatus(0); //TODO:what is the status of order when its been only set?
				//start the Order Controller to insert order into database
				((OrdersOccasionalOrderModel) models
						.get("ordersOccasionalOrderModel"))
						.createOccasionalOrder(bean);			
				} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	

		}
			
		
	}
	
	private void CreateTemporaryOrder() {
		boolean isValidForm=false;
		Orders bean = new Orders();
		NumericValidator verifyID = new NumericValidator();
		Time24HoursValidator verifyTime = new Time24HoursValidator();
		DateValidator verifyDate = new DateValidator();
		EmailValidator verifyEmail = new EmailValidator();

		
		OrderTemporaryForm form = view.getOrderTemporaryViewForm();

			
		if(form.getTextCID().getText().isEmpty() || form.getCarNo_field().getText().isEmpty() || form.getLotNumField().getText().isEmpty() || 
				form.gethTimeLeave_field().getText().isEmpty() || form.getmTimeLeave_field().getText().isEmpty() || form.gethTimeStart_field().getText().isEmpty()||
				form.getmTimeStart_field().getText().isEmpty() )
        {
        	JOptionPane.showMessageDialog(null,"Please fill in all fields","Invalid Input Error", JOptionPane.ERROR_MESSAGE);
		    isValidForm = false;
		    return;
        }
        
		 //Parse all data	
		String ID = form.getTextCID().getText();
		String carNo = form.getCarNo_field().getText();
		String email = form.getEmail_field().getText();
		int lot = Integer.parseInt(form.getLotNumField().getText());
		int leaveHours1 = Integer.parseInt(form.gethTimeLeave_field().getText());
		int leaveMinutes1 = Integer.parseInt(form.getmTimeLeave_field().getText());
		String time1 = form.gethTimeLeave_field().getText() +":"+form.getmTimeLeave_field().getText();
		int startHours2 = Integer.parseInt(form.gethTimeStart_field().getText());
		int startMinutes2 = Integer.parseInt(form.getmTimeStart_field().getText());
		String time2 = form.getmTimeStart_field().getText() +":"+form.getmTimeStart_field().getText();
		
		int day1=form.getDateChooser().getJCalendar().getDayChooser().getDay();
		int month1=form.getDateChooser().getJCalendar().getMonthChooser().getMonth()+1;
		int year1=form.getDateChooser().getJCalendar().getYearChooser().getYear();
		String date1 = Integer.toString(day1)+"/"+ Integer.toString(month1) +"/"+ Integer.toString(year1);
		int day2=form.getDateChooser().getJCalendar().getDayChooser().getDay();
		int month2=form.getDateChooser().getJCalendar().getMonthChooser().getMonth()+1;
		int year2=form.getDateChooser().getJCalendar().getYearChooser().getYear();
		String date2 = Integer.toString(day2)+"/"+ Integer.toString(month2) +"/"+ Integer.toString(year2);
		String dateFormat = "dd/MM/yyyy";
		
		//Input Validity Check
		if (ID.equals("") || carNo.equals("") || lot == 0 || Integer.parseInt(ID)<0  || !verifyID.validate(carNo)) {
			JOptionPane.showMessageDialog(null,"Invalid ID Entered,Please Re-Enter","Invalid Input Error", JOptionPane.ERROR_MESSAGE);
			isValidForm = false;
		}
		else if (time1.equals("") || time2.equals("") || !verifyTime.validate(time1) || !verifyTime.validate(time2) ) {
				JOptionPane.showMessageDialog(null,"Invalid Time Entered,Please Re-Enter","Invalid Time Error", JOptionPane.ERROR_MESSAGE);
				isValidForm = false;
		}
		else if (date1.equals("") || date2.equals("") || !verifyDate.isThisDateValid(date1, dateFormat) || !verifyDate.isThisDateValid(date2, dateFormat)) {
			JOptionPane.showMessageDialog(null,"Invalid Date Entered,Please Re-Enter","Invalid Date Error", JOptionPane.ERROR_MESSAGE);
			isValidForm = false;
	   }
	   else if (email.equals("") || !verifyEmail.validate(email)) {
			JOptionPane.showMessageDialog(null,"Invalid Email Entered,Please Re-Enter","Invalid Email Error", JOptionPane.ERROR_MESSAGE);
			isValidForm = false;
	   }
	   else if (email.equals("") || !verifyEmail.validate(email)) {
			JOptionPane.showMessageDialog(null,"Invalid Email Entered,Please Re-Enter","Invalid Email Error", JOptionPane.ERROR_MESSAGE);
			isValidForm = false;
	   }
	   else{
			isValidForm = true;
		}
		
		if(isValidForm==true){
			 try {
				Timestamp startTimeStamp=customTimestamp.makeTimestamp(year1,month1,day1,Integer.parseInt(form.gethTimeStart_field().getText()),Integer.parseInt(form.getmTimeStart_field().getText()),02,02);
				Timestamp endTimeStamp=customTimestamp.makeTimestamp(year2,month2,day2,Integer.parseInt(form.gethTimeLeave_field().getText()),Integer.parseInt(form.getmTimeLeave_field().getText()),02,02);
				//Check that startDate Timestamp is before leaveDate Timestamp
				if (startTimeStamp.compareTo(endTimeStamp) > 0) {
					JOptionPane.showMessageDialog(null,"Invalid Dates,Please Re-Enter","Invalid Date Error", JOptionPane.ERROR_MESSAGE);
					isValidForm = false;
					return;
			   }
		
				bean.setUid(ID);
				bean.setType("Temporary");
				bean.setCarNo(carNo);
				bean.setStartTime(startTimeStamp);
				bean.setLeaveTime(endTimeStamp);
				bean.setLotNo(lot);
				bean.setEmail(email);
				bean.setStatus(0); //TODO:what is the status of order when its been only set?
				//start the Order Controller to insert order into database
				((OrdersTemporaryModel) models.get("ordersTemporaryModel"))
				.createTemporaryOrder(bean);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
		
			}
		}
}
	
	
private void CancelOrder() {

	boolean isValidForm=false;
		Orders bean; // order to send
		CancelOrderForm form = view.getCancelOrderViewForm();


		NumericValidator verifyID = new NumericValidator(); // create validator
															// to cheack the id
		
		 if(form.getTextOrderID().getText().isEmpty() || form.getTextUserId().getText().isEmpty())
			{
				JOptionPane.showMessageDialog(null,"Please fill in all fields","Invalid Input Error", JOptionPane.ERROR_MESSAGE);
				isValidForm = false;
				return;
			}
		
		 int OID = Integer.parseInt(form.getTextOrderID().getText());// get the text box from gui
		 String UID = form.getTextUserId().getText();

		if (Integer.parseInt(UID)<0  && OID > 0) { // wrong input
			JOptionPane.showMessageDialog(null,
					"Invalid ID Entered,Please Re-Enter",
					"Invalid Input Error", JOptionPane.ERROR_MESSAGE);
		} else { // good input
			try {
				bean = new Orders();
				bean.setOid(OID);
				bean.setUid(UID);
				((OrdersCancelOrderModel) models.get("ordersCancelOrderModel"))
				.cancelOrder(bean);
				} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}
			
    
    private void TrackOrder(){
    	NumericValidator verifyID = new NumericValidator();
		Orders bean; // order to send
    	OrderTrackForm form = view.getOrderTrackViewForm();
    	Integer orderId = Integer.parseInt(form.getTextOrderID().getText());
    	if(orderId<0){
    		JOptionPane.showMessageDialog(null,
					"Invalid ID Entered,Please Re-Enter",
					"Invalid Input Error", JOptionPane.ERROR_MESSAGE);
    	}else{
    		bean = new Orders();
			bean.setOid(orderId);
    		
    	((OrdersTrackModel) models.get("ordersTrackModel"))
		.trackOrder(bean);
    	}
    }

	@Override
	public void addModel(String key, Object model) {
		models.put(key, model);
	}

	@Override
	public void addView(Object applicationView) {
		this.view = (OrderGuestView) applicationView;
	}

	@Override
	public void addModel(Object model) {	

	}

}
